package org.momo.rpc.springboot.starter.bootstrap;

import org.momo.rpc.client.ChannelHolder;
import org.momo.rpc.config.config.RpcConfig;
import org.momo.rpc.config.RpcConfigLoader;
import org.momo.rpc.extention.ExtensionLoader;
import org.momo.rpc.registry.ConsumerRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

public class RpcClientStarter implements ImportBeanDefinitionRegistrar {

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry, BeanNameGenerator importBeanNameGenerator) {
        // config
        RpcConfigLoader.init();
        RpcConfig rpcConfig = RpcConfigLoader.getRpcConfig();

        // 启动 consumer register
        ConsumerRegistry consumerRegistry = ExtensionLoader.getExtensionLoader(ConsumerRegistry.class).getExtension(rpcConfig.getRegistry());
        try {
            consumerRegistry.initRegistryClient(rpcConfig.getRegistryConfig());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        Runtime.getRuntime().addShutdownHook(new Thread(ChannelHolder::closeAllChannel));

        ImportBeanDefinitionRegistrar.super.registerBeanDefinitions(importingClassMetadata, registry, importBeanNameGenerator);
    }

}
